package com.zyf.ppx.fragment

import android.content.Intent
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.AbsListView
import android.widget.RelativeLayout
import android.widget.Toast
import cn.jzvd.JZMediaManager
import cn.jzvd.Jzvd
import cn.jzvd.JzvdMgr
import cn.jzvd.JzvdStd
import com.bumptech.glide.Glide
import com.cooltechworks.views.shimmer.ShimmerRecyclerView
import com.google.gson.Gson
import com.zyf.connotation.BaseFragment
import com.zyf.ppx.R
import com.zyf.ppx.adapter.RecyclerAdapter
import com.zyf.ppx.bean.Connotion
import com.zyf.ppx.bean.Data
import com.zyf.ppx.presenter.ConnotationPresenter
import com.zyf.ppx.ui.DetailsActivity
import com.zyf.ppx.utils.ViewUtils
import com.zyf.ppx.view_interface.NetInterface
import kotlinx.android.synthetic.main.home_fragment.view.*


class HomeFragment :BaseFragment(), NetInterface<Connotion> {
    var swipe: SwipeRefreshLayout?=null
    var recycle: ShimmerRecyclerView?= null
    var animationSet: AnimationSet? = null
    var float_btn: FloatingActionButton? =null
    var floatBthRefresh = false
    var refreshMode = false
    var mLayoutInflater:LayoutInflater? = null
    var presenter: ConnotationPresenter = ConnotationPresenter(this)
    var adapter: RecyclerAdapter? = null
    var type = "1"
    var feedCount  = 1
    var videoplayer:JzvdStd?=null
    override fun initView(inflater: LayoutInflater?, container: ViewGroup?): View? {
        return inflater?.inflate(R.layout.home_fragment,container,false)
    }

    override fun initFindViewById(view: View?) {
        type = arguments?.getString("type")!!
        mLayoutInflater = LayoutInflater.from(baseActivity)
        swipe = view?.swipe
        recycle = view?.recycle
        float_btn = view?.float_btn
        swipe?.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light)
        swipe?.setOnRefreshListener {
            netData(true)
        }
        recycle?.layoutManager = LinearLayoutManager(baseActivity)
        recycle?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                val layoutManager = recyclerView!!.layoutManager as LinearLayoutManager
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                //当前屏幕所看到的子项个数
                val visibleItemCount = layoutManager.childCount
                //当前RecyclerView的所有子项个数
                val totalItemCount = layoutManager.itemCount
                //RecyclerView的滑动状态
                when (newState) {
                    AbsListView.OnScrollListener.SCROLL_STATE_IDLE -> if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 ) {
                        netData(false)
                    }
                }
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
        animationSet = AnimationSet(true)
        var rotate = RotateAnimation(0f,360f, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f)
        rotate.duration = 1000
        rotate.repeatCount = -1
        rotate.interpolator = LinearInterpolator()
        animationSet?.addAnimation(rotate)
        float_btn?.setOnClickListener {
            if(!floatBthRefresh){
                swipe?.setProgressViewOffset(false, 0, 48)
                swipe?.isRefreshing = true
                recycle?.scrollToPosition(0)
                netData(true)
            }
        }
        recycle?.addOnChildAttachStateChangeListener(object :RecyclerView.OnChildAttachStateChangeListener{
            override fun onChildViewDetachedFromWindow(view: View?) {
                var jzvd = view?.findViewById<Jzvd>(R.id.videoplayer)
                if (jzvd?.jzDataSource != null && jzvd?.jzDataSource.containsTheUrl(JZMediaManager.getCurrentUrl())) {
                    val currentJzvd = JzvdMgr.getCurrentJzvd()
                    if (currentJzvd != null && currentJzvd.currentScreen != Jzvd.SCREEN_WINDOW_FULLSCREEN) {
                        Jzvd.releaseAllVideos()
                    }
                }
            }

            override fun onChildViewAttachedToWindow(view: View?) {

            }
        })
        recycle?.showShimmerAdapter()
        netData(true)
    }
    fun netData(isTop:Boolean){
        floatBthRefresh = true
        float_btn?.startAnimation(animationSet)
        presenter.getConnotation(type,feedCount)
        refreshMode = isTop
        feedCount++
    }
    override fun initData() {

    }

    override fun result(data: Connotion) {
        swipe?.isRefreshing = false
        recycle?.hideShimmerAdapter()
        floatBthRefresh = false
        float_btn?.clearAnimation()
        var iterators = data.data.iterator()
        var dataSorse = data.data.filter {
            it.item!=null
        }
        while (iterators.hasNext()){
            if(iterators.next().item==null){

            }
        }
        Toast.makeText(baseActivity,data.tips, Toast.LENGTH_SHORT).show()
        if(!refreshMode&&adapter!=null){
            adapter?.data?.addAll(dataSorse)
            adapter?.notifyDataSetChanged()
        }else{
            adapter = RecyclerAdapter(dataSorse)
            recycle?.adapter = adapter
            adapter?.setOnItemClickListener { _, view, pos ->
                videoplayer = view.findViewById(R.id.videoplayer)
                var intent = Intent(activity, DetailsActivity::class.java)
                if(adapter!!.data[pos].item?.item_type==2){
//                videoplayer.startWindowTiny()
                    var params = videoplayer?.layoutParams as RelativeLayout.LayoutParams
                    var visibility = videoplayer?.visibility
                    var video = JzvdStd(videoplayer?.context)
                    video.setUp(adapter!!.data[pos].item?.video?.video_low?.url_list!![0].url,"",Jzvd.SCREEN_WINDOW_NORMAL)
                    video.layoutParams = params
                    video.visibility = visibility!!
                    video.id = R.id.videoplayer
                    Glide.with(activity!!).load(adapter!!.data[pos].item?.video?.cover_image?.url_list!![0].url).thumbnail(0.1f).into(video?.thumbImageView!!)
                    ViewUtils.videoplayer =videoplayer
                    (videoplayer?.parent as RelativeLayout).addView(video)
                    (videoplayer?.parent as RelativeLayout).removeView(videoplayer)
                }
                intent.putExtra("data",Gson().toJson(adapter!!.data[pos].item.note))
                intent.putExtra("name",adapter!!.data[pos].item.author.name)
                intent.putExtra("image",adapter!!.data[pos].item.author.avatar.download_list[0].url)
                intent.putExtra("item_type",adapter!!.data[pos].item?.item_type)
                intent.putExtra("item_id",adapter!!.data[pos].item?.item_id_str)
                startActivity(intent)
            }
        }
    }

    override fun error(error: String?) {
        swipe?.isRefreshing = false
        floatBthRefresh = false
        float_btn?.clearAnimation()
    }
}